function value_kth=find_kth(list,k,flag);
%value_kth=find_kth(list,k,flag):find kth element in the list
%list:nx1 list
%k: pisitive integer
%flag:0:kth smallest,1:kth 


if k<1
    disp('k should be a pisitive integer ');
    return;
end
list=reshape(list,[],1);
if size(list,1)<k
    disp('the list is too short for finding the kth element');
    return;
end
pivot=list(1);
list_s=[];
list_g=[];

for index=2:size(list,1)
    if list(index,1)>=pivot
        list_g=[list_g; list(index,1)];
    else
        list_s=[list_s;list(index,1)];
    end
end
if flag%largest
    list_g_size=size(list_g,1);
    if list_g_size==k-1
        value_kth=pivot;
    else if list_g_size>k-1
        value_kth = find_kth(list_g,k,flag);
        else
        value_kth = find_kth(list_s,k-list_g_size-1,flag);
        end
    end
else%smallest
    list_s_size=size(list_s,1);
    if list_s_size==k-1
        value_kth=pivot;
    else
        if list_s_size>k-1
        value_kth = find_kth(list_s,k,flag);
        else
        value_kth = find_kth(list_g,k-list_s_size-1,flag);
        end
    end
end
end